﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
using Microsoft.SharePoint.Utilities;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;
using SharePointPowerToys.BusinenssObjects;


namespace SharePointPowerToys
{//inconsiquential change
    class DefaultOptions : EditorPart
    {
        TextBox _urls;
        ConfigurationChooser _chooser;

        public DefaultOptions(string webPartId)
        {

            this.ID = "DefaultOptions" + webPartId;
            this.Title = "Power Query Web Part";

        }

        protected override void OnLoad(EventArgs e)
        {
            _chooser.Click += new EventHandler(_chooser_Click);
            base.OnLoad(e);
        }


        void _chooser_Click(object sender, EventArgs e)
        {
            //SettingOption s = (SettingOption)sender;
            PowerQueryWebPart webPart = (PowerQueryWebPart)this.WebPartToEdit;
            //if (webPart != null)
            //{
            //    webPart.CacheResultsSeconds = s.CacheResultsSeconds;
            //    webPart.CacheSourceSeconds = s.CacheSourceSeconds;
            //    webPart.DataProviderAssemblyClass = s.DataProviderAssemblyClass;
            //    webPart.DataProviderParameters = s.DataProviderParameters;
            //    webPart.ItemLimit = s.ItemLimit;
            //    webPart.ListName = s.ListName;
            //    webPart.ShowRefreshTime = s.ShowRefreshTime;
            //    webPart.SiteUrl = s.SiteUrl;
            //    webPart.XslTransformFile = s.XslTransformFile;
            //}
            webPart.XslTransformFile = "hi";
            //throw new NotImplementedException();
        }

        //void _chooser_Click(SettingOption settingOption)
        //{
        //    //set the webpart settings based on the settingOption
        //    throw new NotImplementedException();
        //}

        protected override void OnPreRender(EventArgs e)
        {

            base.OnPreRender(e);
        }



        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            _urls = new TextBox();
            _chooser = new ConfigurationChooser();

            PowerQueryWebPart webPart = (PowerQueryWebPart)this.WebPartToEdit;
            if (webPart != null)
            {
                _urls.Text = webPart.ConfigUrls;
                if (webPart.SelectedSettingKey != null) 
                {
                 _chooser.SelectedSettingKey = webPart.SelectedSettingKey;
                }
                else
                {
                 _chooser.SelectedSettingKey = "";
                }
            }

            
            
            //this.Controls.Add(_message);
            Table sectionTable = new Table();
            sectionTable.CellPadding = 0;
            sectionTable.CellSpacing = 0;
            sectionTable.Style["border-collapse"] = "collapse";
            sectionTable.Attributes.Add("width", "100%");
            addToolPaneControl(sectionTable, "Pre-Configuration URLs", createConfigurationUrlTextarea());
            //createOptionsFromSettings(sectionTable);

            _chooser.SettingOptions = GetSettingOptions();
            _chooser.SelectedSettingKey = webPart.SelectedSettingKey;
            
            Controls.Add(sectionTable);
            Controls.Add(_chooser);

        }

        private void createOptionsFromSettings(Table sectionTable)
        {
            string[] myUrls = _urls.Text.Split();
            for (int i = 0; i < myUrls.Length; i++)
            {
                //pass it to a class that knows how to tell what kind of document it is or if it's even appropriate at all and gernerate the appropriate otpions for it

                // but for now because I want to see it work I'll just create the options for the one list
                addToolPaneControl(sectionTable, "&nbsp;", createConfigurationOptions(myUrls[i]));
            }

        }

        private Control createConfigurationOptions(string url)
        {

            //get document
            //read settings
            return new Control();

        }

        private Table createConfigurationUrlTextarea()
        {
            Table table = new Table();
            table.Width = Unit.Percentage(100.0);
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.VerticalAlign = VerticalAlign.Top;

            _urls.TextMode = TextBoxMode.MultiLine;
            _urls.Rows = 3;
            _urls.Width = Unit.Percentage(100.0);

            cell.Controls.Add(_urls);
            row.Cells.Add(cell);
            table.Rows.Add(row);

            TableCell cell2 = new TableCell();
            TableRow row2 = new TableRow();
            Button refresh = new Button();
            refresh.Click += new EventHandler(refresh_Click);
            refresh.Text = "Refresh";
            refresh.ToolTip = "After entering url of preconfig above.  Click refresh to see available options.";
            cell2.Controls.Add(refresh);
            row2.Cells.Add(cell2);
            table.Rows.Add(row2);
            return table;

        }

        static void refresh_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private static void addToolPaneControl(Table sectionTable, string label, Control newControl)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Controls.Add(new LiteralControl("<div class=\"UserSectionHead\">"));
            Label child = new Label();
            child.Text = SPHttpUtility.HtmlEncode(label);
            cell.Controls.Add(new LiteralControl("<b>"));
            cell.Controls.Add(child);
            cell.Controls.Add(new LiteralControl(":"));
            cell.Controls.Add(new LiteralControl("</b>"));
            cell.Controls.Add(new LiteralControl("</div>"));
            cell.Controls.Add(new LiteralControl("<div class=\"UserSectionBody\"><div class=\"UserControlGroup\"><nobr>"));
            cell.Controls.Add(newControl);
            cell.Controls.Add(new LiteralControl("</nobr></div></div>"));
            cell.Controls.Add(new LiteralControl("<div style='width:100%' class='UserDottedLine'></div>"));
            row.Cells.Add(cell);
            sectionTable.Rows.Add(row);
        }

        public SortableCollection<SettingOption> GetSettingOptions()
        {
            SortableCollection<SettingOption> settingOptionList = new SortableCollection<SettingOption>();
            SettingOption s = new SettingOption();

            s.Title = "Custom";
            s.Description = "The setting below are custom settings.";
            s.Key = "0";
            settingOptionList.Add(s);
            /*
             *
             * Code to retrieve Employees from Database and populate a 
             * SortableCollection of Employee objects
              Checkk for duplicates while adding
             */
            string[] myUrls = _urls.Text.Split();
            foreach (string url in myUrls)
            {
                XNamespace slashNamespace = "http://purl.org/rss/1.0/modules/slash/";

                XslCompiledTransform xslTransform = Helpers.TransformLoad("WSS_LIST_RSS_FIELDS.xsl");

                //XmlReader xmlReader = XmlReader.Create(
                //TextReader textReader = new textReader();
                string xml = string.Empty;
                if (url != string.Empty)
                {
                    try
                    {
                        // throws error if win-auth rss feed
                        string sourceXml = Helpers.GetFile(url);
                        StringReader sr = new StringReader(sourceXml);
                        XmlReader xmlReader = XmlReader.Create(sr);
                        xml = Helpers.TransformGetString(xslTransform, xmlReader);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                if (xml != string.Empty)
                {
                    XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
                    XDocument configFeed = XDocument.Load(xmlReader);
                    
                    var options = from item in configFeed.Descendants("item")
                                  select new //(s => new SettingOption {
                                  {
                                      Title = Helpers.GetElementString(item, "title"),
                                      //ThumbNail = Helpers.GetUrlFromAnchor(Helpers.GetElementString(item, "Image")),
                                      ThumbNail = Helpers.GetElementString(item, "Image"),
                                      Description = Helpers.GetElementString(item, "Description"),
                                      Link = Helpers.GetElementString(item, "link"),
                                      SiteUrl = HttpUtility.HtmlDecode(Helpers.GetElementString(item, "SiteUrl")),
                                      ListName = Helpers.GetElementString(item, "ListName"),
                                      DataProviderParameters = HttpUtility.HtmlDecode(Helpers.GetElementString(item, "DataProviderParameters")),
                                      ItemLimit = Helpers.GetElementString(item, "ItemLimit", "0"),
                                      SecondsToCacheDataSource = Helpers.GetElementString(item, "SecondsToCacheDataSource", "0"),
                                      XSLTransformFileURL = HttpUtility.HtmlDecode(Helpers.GetElementString(item, "XSLTransformFileURL")),
                                      SecondstoCacheResults = Helpers.GetElementString(item, "SecondstoCacheResults", "0"),
                                      ShowRefreshTime = Helpers.GetElementString(item, "ShowRefreshTime", "No"),
                                      DebugMode = Helpers.GetElementString(item, "DebugMode", "No"),
                                  };
                    int i = 0;
                    foreach (var item in options)
                    {
                        ++i;
                        SettingOption settingOption = new SettingOption();
                        settingOption.Key = i.ToString();
                        settingOption.Title = item.Title;
                        settingOption.Image = item.ThumbNail;
                        settingOption.Description = item.Description;
                        settingOption.More = item.Link;
                        settingOption.SiteUrl = item.SiteUrl;
                        settingOption.ListName = item.ListName;
                        settingOption.DataProviderParameters = item.DataProviderParameters;
                        settingOption.ItemLimit = Convert.ToInt64(item.ItemLimit.Replace(",", string.Empty));
                        settingOption.CacheResultsSeconds = Convert.ToInt64(item.SecondstoCacheResults.Replace(",", string.Empty));
                        settingOption.CacheSourceSeconds = Convert.ToInt64(item.SecondsToCacheDataSource.Replace(",", string.Empty));
                        settingOption.XslTransformFile = item.XSLTransformFileURL;
                        settingOption.ShowRefreshTime = (item.ShowRefreshTime.ToLower() == "yes" && item.ShowRefreshTime.ToLower() == "true");

                        // check for duplicates

                        //iff no duplicates the and
                        settingOptionList.Add(settingOption);
                    }
                }
            }
            
            return settingOptionList;
        } 



        public override bool ApplyChanges()
        {

            EnsureChildControls();
            applySettings();
            
            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            syncSettings();
        }

        private void applySettings()
        {

            PowerQueryWebPart webPart = (PowerQueryWebPart)this.WebPartToEdit;
            if (webPart != null)
            {
                if (_chooser.ddl.SelectedValue.ToString() != "0")
                {
                    SettingOption setting = _chooser.SettingOptions.getItemFromKey(_chooser.ddl.SelectedValue.ToString());
                    webPart.CacheResultsSeconds = setting.CacheResultsSeconds;
                    webPart.CacheSourceSeconds = setting.CacheSourceSeconds;
                    webPart.DataProviderAssemblyClass = setting.DataProviderAssemblyClass;
                    webPart.ItemLimit = setting.ItemLimit;
                    webPart.ListName = setting.ListName;
                    webPart.ShowRefreshTime = setting.ShowRefreshTime;
                    webPart.SiteUrl = setting.SiteUrl;
                    webPart.Title = setting.Title;
                    webPart.Description = setting.Description;
                    webPart.XslTransformFile = setting.XslTransformFile;
                    webPart.DataProviderParameters = setting.DataProviderParameters;
                    webPart.ConfigUrls = _urls.Text;
                }
                webPart.SelectedSettingKey = _chooser.ddl.SelectedValue;
            }
        }

        private void syncSettings()
        {
            PowerQueryWebPart webPart = (PowerQueryWebPart)this.WebPartToEdit;
            if (webPart != null)
            {
                _urls.Text = webPart.ConfigUrls;
                if (_chooser.ddl != null) 
                {
                    _chooser.ddl.SelectedValue = webPart.SelectedSettingKey;
                }
                
            }
        }
    }
}
